using System;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

//CID 0230 //2009.02.24 //Begin
namespace InfoJetSoft.Service.Util
{
	/// <summary>
	/// Summary description for SDSIder.
	/// </summary>
	class SDSIdUtil
	{
		public static void refreshIds( Form form )
		{
			foreach( DataObject dataObject in form.Manifest.DataObjectList )
			{
				foreach( View view in form.Manifest.ViewList )
				{
					if( view.SDSInView.SDSList != null && view.SDSInView.SDSList.Contains( dataObject.Name ) )
					{
						XmlDocument dataDoc = form.DataTable[ dataObject.Name ] as XmlDocument;
						if( dataDoc != null )
						{
							setElementId( dataObject, dataDoc.DocumentElement, 0 );
							break;
						}
					}
				}
			}
		}

		//CID 0230 //2009.02.25 //Begin
		public static void refreshIds( Form form, DataObject dataObject, XmlDocument dataDoc )
		{
			foreach( View view in form.Manifest.ViewList )
			{
				if( view.SDSInView.SDSList != null && view.SDSInView.SDSList.Contains( dataObject.Name ) )
				{
					setElementId( dataObject, dataDoc.DocumentElement, 0 );
					break;
				}
			}
		}
		//CID 0230 //2009.02.25 //End

		private static int setElementId( DataObject dataObject, XmlElement element, int index )
		{
			//CID 0230 //2009.02.26 //Begin
			element.SetAttribute( JetConstant.JetId, "_s_" + dataObject.Id + "_" + index );
			index ++;
			//CID 0230 //2009.02.26 //End
			XmlNodeList childElementList = element.SelectNodes( "*" );
			if( childElementList.Count > 0 )
			{
				int next = index;
				foreach( XmlElement childElement in childElementList )
				{
					next = setElementId( dataObject, childElement, next );
				}
				return next;
			}
			else
			{
				return index;
			}
		}

        //CID 0755 //2011.01.06 //Begin
        public static DataObject findDataObjectByJetId(Form form, string jetId)
        {
            //remove _s_
            jetId = jetId.Substring(3, jetId.Length - 3);
            int index = jetId.IndexOf("_");
            string sdsId = jetId.Substring(0, index);
            foreach (DataObject dataObject in form.Manifest.DataObjectList)
            {
                if (dataObject.Id.Equals(sdsId))
                {
                    return dataObject;
                }
            }
            return null;
        }
        //CID 0755 //2011.01.06 //End
	}
}
//CID 0230 //2009.02.24 //End
